<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"  label-width="120px" :label-position="labelPosition">
      <el-form-item label="订单号" prop="pzbh">
        <el-input
          v-model="queryParams.pzbh"
          placeholder="请输入订单号"
          clearable
           @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="warehousePropertyDate">
        <el-date-picker
            v-model="warehousePropertyDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="warehousePropertyDateChange()">
            </el-date-picker>
      </el-form-item>
      <el-form-item label="条码" prop="sptm">
        <el-input
          v-model="queryParams.sptm"
          placeholder="请输入条码"
          clearable
           @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="柜号/批号" prop="spgh">
        <el-input
          v-model="queryParams.spgh"
          placeholder="请输入柜号/批号"
          clearable
           @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="旧货权人" prop="khmc1">
        <el-select
            v-model="queryParams.khmc1"
            placeholder="请输入旧货权人"
            clearable
            style="width: 240px"
            @change="changewarehousePropertyO"
            filterable
            :loading="selectClient3Loading"
        >
          <el-option
              v-for="(item,index) in selectClient3List"
              :key="index"
              :label="item.khmc"
              :value="item.khmc"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="新货权人" prop="khmc2">
        <el-select
            v-model="queryParams.khmc2"
            placeholder="请输入新货权人"
            clearable
            style="width: 240px"
            @change="changewarehousePropertyX"
            filterable
        >
          <el-option
              v-for="(item, index) in selectClient3List"
              :key="index"
              :label="item.khmc"
              :value="item.khmc"
          />
        </el-select>
      </el-form-item>      
      <el-form-item label="仓库" prop="spckmc">
        <el-input
          v-model="queryParams.spckmc"
          placeholder="请输入仓库"
          clearable
           @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="仓位" prop="ckcw">
        <el-input
          v-model="queryParams.ckcw"
          placeholder="请输入仓位"
          clearable
           @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item >
        <el-checkbox v-model="queryParams.jqcz" label="精确查找" true-label="1" @change="getList"></el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
     <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="handleWarehousePropertyAdd" v-hasPermi="['zhcloud:hqzy:add']">货转办单</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button  type="primary" plain size="mini" @click="handelPatchAudit"  :disabled="selection.length === 0" v-hasPermi="['zhcloud:hqzy:audit']">批量审核</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="handleExport" :disabled="selection.length === 0" v-hasPermi="['zhcloud:hqzy:export']">导出</el-button>
        </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="warehouseInList"
      :show-summary="false"
      :summary-method="getSummaries"
      @selection-change="handleSelectionChange"
    >
      <af-table-column type="selection" width="50" align="center" />  
      <af-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="left">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleOpenDetail(scope.row)"
            v-hasPermi="['zhcloud:hqzy:detail']"
          >详细</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePrint(scope.row)"
            v-hasPermi="['zhcloud:hqzy:print']"
          >打印</el-button>
        </template>
      </af-table-column>
      <af-table-column label="单号" prop="pzbh"/>
      <af-table-column label="旧货权人" prop="khmc" />
      <af-table-column label="新货权人" prop="khmc1" />
      <af-table-column label="日期" prop="ssrqid"/>
      <af-table-column label="创建时间" prop="prrq"/>
      <af-table-column label="制单人" prop="rsopmc"/>
      <af-table-column label="转移件数" prop="spjs"/>
      <af-table-column label="转移吨数" prop="spsl"/>
      <af-table-column label="备注" prop="dzbz" width="150" :show-overflow-tooltip="true"/>
      <af-table-column label="审核人" prop="shrsmc"/>
      <af-table-column label="审核日期" prop="shrqid"/>
      <af-table-column label="审核状态" prop="shzt"/>
    </el-table>
     <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getList"
      />
  </div>

</template>

<script>
import { listwarehouseProperty, warehousePropertyAudit} from "@/api/storage/commonGoods/warehouseProperty";
import { selectClient3 } from "@/api/storage/customer";
import ExportJsonExcel from 'js-export-excel'
import { NUMBER_DIDGIT, WEIGHT_DIGIT } from '@/utils/constant'
import { formatDate, calculateDays } from '@/utils'

export default {
  name: "WarehouseProperty",
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //对齐方式
      labelPosition:"right",
      //加载列表
      loading: true,
      //客户加载
      selectClient3Loading: true,
      //审核状态
      auditState:[{
        value: "未审核",
        label:"未审核"
      },{
        value: "已审核",
        label:"已审核"
      }],
      warehousePropertyDate:'',
      // 查询参数
      queryParams: {
        ckcw: "",
        isBa: "",
        jqcz: "",
        khmc1: "",
        khmc11: "",
        khmc2: "",
        khmc22: "",
        khpb: 0,
        pzbh: "",
        rqid1: "",
        rqid2: "",
        shopId: 0,
        spckidis: [],
        spckmc: "",
        spgh: "",
        sptm: ""
      },
      //获取客户参数
      selectCustomerQuery: {
        khmc1: "",
      },
      //新旧货权人返回列表
      selectClient3List:[],
      //批量审核数据
      selection:[],
      // 货物入仓列表
      warehouseInList: [],
      //页数
      pageSize: 10,
      //页码
      pageNum:1,
      // 总条数
      total: 0,
    };
  },
  beforeRouteEnter(to, from, next) {
    const params = to.params
    next(vm => {   
      if(Object.keys(params).length > 0) {
        if(to.params.refresh == true) {
          vm.getList()
        }
      }
    })
  },
  created() {
    this.selectClient3Select()
    this.getList();
  },
  methods: {
    /**获取新旧货权人 */
    selectClient3Select() {
      this.selectClient3Loading = true
      selectClient3(this.selectCustomerQuery).then(response => {
        this.selectClient3List = response.data
        this.selectClient3Loading = false
      });
    },
    /** 查询货权转移列表 */
    getList() {
      this.loading=true
      listwarehouseProperty(this.queryParams, {pageNum:this.pageNum, pageSize:this.pageSize}).then(response => {
        this.warehouseInList = response.rows;
        this.total = response.total;
        this.loading=false
      });
    },
     /**选择创建时间 */
    warehousePropertyDateChange() {
      this.queryParams.rqid1 = this.warehousePropertyDate?this.warehousePropertyDate[0]:""
      this.queryParams.rqid2 = this.warehousePropertyDate?this.warehousePropertyDate[1]:""
      this.getList()
    },
    /** 改变新货权人*/
    changewarehousePropertyX() {
      this.getList()
    },
     /** 改变旧货权人*/
    changewarehousePropertyO() {
      this.getList()
    },
    /**批量审核 */
    auditWarehouseProperty() {
      const data = []
      const selection = this.selection
      for(let i in selection) {
        data[i] = selection[i].dzid
      }
      this.$modal.loading("数据正在审核中，请稍等...")
      warehousePropertyAudit(data).then(response => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('审核成功！')
        this.getList()
      }).catch(()=> {
        this.$modal.closeLoading()
      })
    },
    //合计
    getSummaries({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if(index === 0) {
          sums[index] = "合计"
			    return
        }
        if ((column.property === "spjs" || column.property === "spsl")) {
          const values = data.map((item) => {
            return parseFloat(this.delcommafy(item[column.property]))
          });
          sums[index] = values.reduce((prev, curr) => {
            if(!prev) prev = 0
            if(!curr) curr = 0
            if(column.property === "spsl") {
              return parseFloat((prev + curr).toFixed(WEIGHT_DIGIT))
            }
             if(column.property === "spjs") {
              return parseFloat((prev + curr).toFixed(NUMBER_DIDGIT))
            }
          }, 0);
        }
      })
      return sums
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNum = 1
      this.getList();
    },

    /** 批量审核*/
    handelPatchAudit() {
      const nowDate = formatDate(Date.now()).split(" ")[0]
      const selection = this.selection
      for(let i in selection) {
        if(selection[i].shzt == "已审核") return this.$modal.msgWarning("已审核的单不允许再次审核！")
      }

       //如果当前时间（审核日期）小于转货日期，则系统提示：转货日期大于当前日期，审核失败！
       if(selection && selection.length > 0) {
        const sortSelection = selection.sort((a,b) => a.ssrqid>b.ssrqid?-1:1)
        if(calculateDays(sortSelection[0].ssrqid, nowDate) < 0) return this.$modal.msgWarning("出仓日期大于当前日期，审核失败！")
      }

      this.$modal.confirm('是否确认次操作？').then(() => {
        this.auditWarehouseProperty()
      }).catch(() => {});
    },

    /** 增加货权转移单*/
    handleWarehousePropertyAdd() {
        this.$router.push({name:"WarehousePropertyMove"})
    },

    /**详情 */
    handleOpenDetail(row) {
      const data = JSON.parse(JSON.stringify(row))
       this.$router.push({path:"/storage/commonGoods/warehouseProperty/warehousePropertyDetail", query:data})
       
    },

    /**打印 */
    handlePrint(row) {
      const data = JSON.parse(JSON.stringify(row))
      this.$router.push({path:"/storage/commonGoods/warehouseProperty/warehousePropertyPrint", query:data})
    },

    /** 导出勾选数据*/
    handleExport() {
      if (this.selection.length > 0) {
        let option = {}
        option.fileName = '货权转移勾选数据'
        option.datas = [
          {
            sheetData: this.selection,//数据
            sheetName: 'sheet',
            //表头数据对应的sheetData数据
            sheetFilter: ['pzbh', 'khmc', 'khmc1', 'ssrqid', 'prrq', 'rsopmc', 'spjs', 'spsl', 'dzbz', 'shrsmc', 'shrqid', 'shzt'],
            sheetHeader: [
              //表头数据
              '单号', '旧货权人', '新货权人', '日期', '创建时间', '制单人','转移件数', '转移吨数','备注', '审核人','审核日期','审核状态'],
          }
        ]
        let excel = ExportJsonExcel(option)
        excel.saveExcel()
      } else {
        this.$modal.msgError('请勾选数据');
      }
    },

     // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
    },
       /**enter键触发 */
    enterClick(e) {
      this.getList()
    },

    /** 刷新数据*/
    refresh() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.selectClient3Select()
      this.getList()
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    },
  }
};
</script>
